package cn.stylefeng.guns.modular.demo.service;

import cn.stylefeng.guns.core.exception.BusinessException;
import cn.stylefeng.guns.core.exception.BusinessExceptionEnum;
import cn.stylefeng.guns.dao.IGoodsService;
import cn.stylefeng.guns.dao.IRuleSupplierService;
import cn.stylefeng.guns.dao.ISaleStockService;
import cn.stylefeng.guns.dao.ISupplierService;
import cn.stylefeng.guns.dao.entity.*;
import cn.stylefeng.guns.dao.service.IGaiaWmsDiaoboMService;
import cn.stylefeng.guns.modular.demo.controller.domain.ReportVO;
import cn.stylefeng.guns.modular.demo.controller.domain.RuleVO;
import cn.stylefeng.guns.modular.demo.controller.domain.YearReportVO;
import cn.stylefeng.roses.kernel.auth.api.exception.AuthException;
import cn.stylefeng.roses.kernel.auth.api.exception.enums.AuthExceptionEnum;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportService {
    @Resource
    private IRuleSupplierService ruleSupplierService;
    @Resource
    private ISaleStockService saleStockService;
    @Resource
    private RuleBizService ruleBizService;
    @Resource
    private ISupplierService supplierService;
    @Resource
    private IGoodsService goodsService;

    @Resource
    private IGaiaWmsDiaoboMService gaiaWmsDiaoboMService;


//    /**
//     * 生成返利报表
//     *
//     * @param outputStream
//     */
//    public void generate(OutputStream outputStream) {
//        try (ExcelWriter excelWriter = EasyExcel.write(outputStream, SaleReportVO.class).build()) {
//
//            Long firstDayOfMonth = RebateDateUtil.getFirstDayOfMonth();
//            Long lastDayOfMonth = RebateDateUtil.getLastDayOfMonth();
//            //月报
//            WriteSheet writeSheet = EasyExcel.writerSheet("月报").build();
//            generateReport(firstDayOfMonth, lastDayOfMonth, TimeTypeEnum.MONTH.getTimeType(), excelWriter, writeSheet);
//            Long lastDayOfSeason = RebateDateUtil.getLastDayOfSeason();
//            Long firstDayOfSeason = RebateDateUtil.getFirstDayOfSeason();
//            //季度报
//            WriteSheet writeSheetSeason = EasyExcel.writerSheet("季度报").build();
//            generateReport(firstDayOfSeason, lastDayOfSeason, TimeTypeEnum.SEASON.getTimeType(), excelWriter, writeSheetSeason);
//
//            Long lastDayOfYeah = RebateDateUtil.getLastDayOfYeah();
//            Long firstDayOfYeah = RebateDateUtil.getFirstDayOfYeah();
//            //年报
//            WriteSheet writeSheetYeah = EasyExcel.writerSheet("年报").build();
//            generateReport(firstDayOfYeah, lastDayOfYeah, TimeTypeEnum.YEAH.getTimeType(), excelWriter, writeSheetYeah);
//        }
//    }


    /**
     * 生成日月季度报表
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public List<ReportVO> generateReport(Long startTime, Long endTime, List<String> supplierIdList, List<String> goodsIdList, List<String> saleStockIdList) {
        log.info("政策生效处理开始...");

        List<String> queryGoodsIdList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(goodsIdList)) {
            queryGoodsIdList.addAll(goodsIdList);
        }

        if (CollectionUtils.isNotEmpty(saleStockIdList)) {
            List<SaleStock> saleStockList = saleStockService.listByIds(saleStockIdList);
            List<String> goodIdList = saleStockList.stream().map(SaleStock::getGoodsId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(goodIdList)) {
                queryGoodsIdList.addAll(goodIdList);
            }
        }
        //生效中的规则
        List<RuleSupplier> ruleSupplierList = ruleSupplierService.getAvailableList(supplierIdList, queryGoodsIdList, startTime, endTime);
//        List<RuleSupplier> ruleSupplierList = ruleSupplierService.list(Wrappers.<RuleSupplier>lambdaQuery()
//                .in(CollectionUtils.isNotEmpty(supplierIdList), RuleSupplier::getSupplierId, supplierIdList)
//                .in(CollectionUtils.isNotEmpty(goodsIdList), RuleSupplier::getGoodsId, goodsIdList)
//                .ge(RuleSupplier::getEffectiveTime, startTime)
//                .le(RuleSupplier::getEffectiveEndTime, endTime));
        if (CollectionUtils.isEmpty(ruleSupplierList)) {
            throw new BusinessException(BusinessExceptionEnum.BUSINESS_DATA_REPEAT, "没有生效中的规则");
//            log.info("没有生效中的规则");
//            return Lists.newArrayList();
        }
        List<ReportVO> reportVOS = Lists.newArrayList();
        //按供应商写
        Map<String, List<RuleSupplier>> supplierMap = ruleSupplierList.stream().collect(Collectors.groupingBy(RuleSupplier::getSupplierId));
        for (Map.Entry<String, List<RuleSupplier>> entry : supplierMap.entrySet()) {
            String key = entry.getKey();
            Supplier supplier = supplierService.getById(key);
            List<RuleSupplier> ruleSuppliers = entry.getValue();
            Map<String, List<RuleSupplier>> goodsMap = ruleSuppliers.stream().collect(Collectors.groupingBy(RuleSupplier::getGoodsId));

            BigDecimal allTicketBigDecimalSupplier = new BigDecimal(0);
            BigDecimal allMoneyBigDecimalSupplier = new BigDecimal(0);
            Integer totalNumSupplier = 0;
            List<ReportVO.GoodsReportVO> goodsReportVOS = Lists.newArrayList();

            for (Map.Entry<String, List<RuleSupplier>> goodsEntry : goodsMap.entrySet()) {
                //商品维度
                String goodsId = goodsEntry.getKey();
                List<RuleSupplier> value = goodsEntry.getValue();
                Goods goods = goodsService.getById(goodsId);

                Integer totalNum = 0;
                BigDecimal allTicketBigDecimal = new BigDecimal(0);
                //todo
                BigDecimal allMoneyBigDecimal = new BigDecimal(0);
                ArrayList<String> allSaleIdList = Lists.newArrayList();
                for (RuleSupplier ruleSupplier : value) {
                    String supplierId = ruleSupplier.getSupplierId();


                    RuleVO ruleVO = ruleBizService.getDetail(ruleSupplier.getRuleId());
                    // 计算真正有效的时间
                    Long effectiveTime = ruleSupplier.getEffectiveTime();
                    Long effectiveEndTime = ruleSupplier.getEffectiveEndTime();
                    // 过滤下
                    if (effectiveEndTime < startTime || effectiveTime > endTime) {
                        continue;
                    }


                    Long realStartTime = startTime > effectiveTime ? startTime : effectiveTime;
                    Long realEndTime = endTime > effectiveEndTime ? effectiveEndTime : endTime;

                    List<ReportDto> reportDtos = saleStockService.sumTotal(realStartTime, realEndTime, supplierId, goodsId, saleStockIdList);
                    if (CollectionUtils.isEmpty(reportDtos)) {
                        continue;
                    }
                    //todo
                    ReportDto reportDto = reportDtos.get(0);
                    String sale = reportDto.getSale();
                    Integer price = reportDto.getPrice();
                    Integer num = Objects.isNull(price) ? 0 : price;
                    String saleIdList = StringUtils.isBlank(sale) ? "" : sale;


                    BigDecimal bigDecimal = calRebate(ruleVO, num);
                    //按比例拆分
                    Integer ticket = ruleVO.getTicket();
                    Integer money = ruleVO.getMoney();
                    BigDecimal ticketRatio = new BigDecimal(ticket).divide(new BigDecimal(100));
                    BigDecimal moneyRatio = new BigDecimal(money).divide(new BigDecimal(100));

                    BigDecimal ticketBigDecimal = bigDecimal.multiply(ticketRatio).setScale(4, RoundingMode.HALF_UP);
                    BigDecimal moneyBigDecimal = bigDecimal.multiply(moneyRatio).setScale(4, RoundingMode.HALF_UP);

                    allTicketBigDecimal = allTicketBigDecimal.add(ticketBigDecimal);
                    allMoneyBigDecimal = allMoneyBigDecimal.add(moneyBigDecimal);
                    allSaleIdList.addAll(List.of(saleIdList.split(",")));
                    totalNum += num;

                }

                if (totalNum > 0) {
                    //商品统计
                    ReportVO.GoodsReportVO goodsReportVO = new ReportVO.GoodsReportVO();
                    goodsReportVO.setCommodityCode(goods.getCommodityCode());
                    goodsReportVO.setCommodityName(goods.getCommodityName());
                    goodsReportVO.setSaleNum(totalNum);
                    goodsReportVO.setCashPrice(allMoneyBigDecimal.setScale(4, RoundingMode.HALF_UP));
                    goodsReportVO.setTicketPrice(allTicketBigDecimal.setScale(4, RoundingMode.HALF_UP));
                    goodsReportVO.setSaleStockIdList(allSaleIdList);
                    goodsReportVOS.add(goodsReportVO);
                }
                totalNumSupplier += totalNum;
                allTicketBigDecimalSupplier = allTicketBigDecimalSupplier.add(allTicketBigDecimal);
                allMoneyBigDecimalSupplier = allMoneyBigDecimalSupplier.add(allMoneyBigDecimal);
            }
            //没有的就过滤了
            if (totalNumSupplier == 0) {
                continue;
            }
            ReportVO reportVO = new ReportVO();
            reportVO.setSaleNum(totalNumSupplier);
            reportVO.setSupplierCode(supplier.getSupplierCode());
            reportVO.setSupplierName(supplier.getName());
            reportVO.setGoodsReportList(goodsReportVOS);
            reportVO.setCashPrice(allMoneyBigDecimalSupplier.setScale(4, RoundingMode.HALF_UP));
            reportVO.setTicketPrice(allTicketBigDecimalSupplier.setScale(4, RoundingMode.HALF_UP));
            reportVOS.add(reportVO);
        }
        return reportVOS;
    }


//    /**
//     * 生成日月季度报表
//     *
//     * @param startTime
//     * @param endTime
//     * @param timeType
//     * @return
//     */
//    public void generateReport(Long startTime, Long endTime, Integer timeType, ExcelWriter excelWriter, WriteSheet writeSheet) {
//        log.info("政策生效处理开始...");
//        //先处理下状态
//        handlerStatus();
//        //生效中的规则
//        List<RuleSupplier> ruleSupplierList = ruleSupplierService.list(Wrappers.<RuleSupplier>lambdaQuery()
////                .in(RuleSupplier::getEffectiveStatus, Lists.newArrayList(EffectiveStatusEnum.ING.getEffectiveStatus())
//        );
//        if (CollectionUtils.isEmpty(ruleSupplierList)) {
//            log.info("没有生效中的规则");
//            return;
//        }
//        //按供应商写
//        Map<String, List<RuleSupplier>> supplierMap = ruleSupplierList.stream().collect(Collectors.groupingBy(RuleSupplier::getSupplierId));
//        for (Map.Entry<String, List<RuleSupplier>> entry : supplierMap.entrySet()) {
//            String key = entry.getKey();
//            Supplier supplier = supplierService.getById(key);
//            List<RuleSupplier> ruleSuppliers = entry.getValue();
//            //商品 规则
//            List<SaleReportVO> reportVOS = Lists.newArrayList();
//            Integer totalNum = 0;
//            BigDecimal allTicketBigDecimal = new BigDecimal(0);
//            BigDecimal allMoneyBigDecimal = new BigDecimal(0);
//            for (RuleSupplier ruleSupplier : ruleSuppliers) {
//                String supplierId = ruleSupplier.getSupplierId();
//                String commodityCode = ruleSupplier.getCommodityCode();
//                List<SaleStock> list = saleStockService.list(Wrappers.<SaleStock>lambdaQuery().eq(SaleStock::getCommodityCode, commodityCode).last(" limit 1"));
//
//                RuleVO ruleVO = ruleBizService.getDetail(ruleSupplier.getRuleId());
//                if (!Objects.equals(timeType, ruleVO.getTimeType())) {
//                    continue;
//                }
//
//                Integer num = saleStockService.sumTotal(startTime, endTime, supplierId, commodityCode);
//                num = Objects.isNull(num) ? 0 : num;
//
//                //每一笔商品返利多少
//                SaleReportVO saleReportVO = new SaleReportVO();
//                saleReportVO.setSaleTime(new Date(startTime));
//                saleReportVO.setSaleNum(num);
//                if (CollectionUtils.isNotEmpty(list)) {
//                    saleReportVO.setCommodityName(list.get(0).getCommodityName());
//                } else {
//                    saleReportVO.setCommodityName("");
//                }
//                saleReportVO.setCommodityCode(commodityCode);
//                if (Objects.nonNull(supplier)) {
//                    saleReportVO.setSupplierCode(supplier.getSupplierCode());
//                    saleReportVO.setSupplierName(supplier.getName());
//                } else {
//                    saleReportVO.setSupplierCode(key + "(已删除)");
//                    saleReportVO.setSupplierName(key + "(已删除)");
//                }
//
//
//                BigDecimal bigDecimal = calRebate(ruleVO, num);
//                //按比例拆分
//                Integer ticket = ruleVO.getTicket();
//                Integer money = ruleVO.getMoney();
//                BigDecimal ticketRatio = new BigDecimal(ticket).divide(new BigDecimal(100));
//                BigDecimal moneyRatio = new BigDecimal(money).divide(new BigDecimal(100));
//
//                BigDecimal ticketBigDecimal = bigDecimal.multiply(ticketRatio).setScale(2, RoundingMode.HALF_UP);
//                BigDecimal moneyBigDecimal = bigDecimal.multiply(moneyRatio).setScale(2, RoundingMode.HALF_UP);
//
//                allTicketBigDecimal = allTicketBigDecimal.add(ticketBigDecimal);
//                allMoneyBigDecimal = allMoneyBigDecimal.add(moneyBigDecimal);
//
//
//                saleReportVO.setCashPrice(moneyBigDecimal.divide(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP));
//                saleReportVO.setTicketPrice(ticketBigDecimal.divide(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP));
//                reportVOS.add(saleReportVO);
//
//                totalNum += num;
//            }
//            //写入商品数据
//            excelWriter.write(reportVOS, writeSheet);
//            //每一笔商品返利多少
//            SaleReportVO saleReportVO = new SaleReportVO();
//            saleReportVO.setSaleNum(totalNum);
//            saleReportVO.setSupplierCode("总计");
//            saleReportVO.setCashPrice(allMoneyBigDecimal.divide(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP));
//            saleReportVO.setTicketPrice(allTicketBigDecimal.divide(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP));
//            //写一个总计
//            excelWriter.write(Collections.singleton(saleReportVO), writeSheet);
//        }
//    }

//    //生成报表数据
//    private List<SaleReportVO> report(List<RuleSupplier> ruleSupplierList, Long startTime, Long endTime, Integer timeType) {
//        HashMap<String, List<SaleReportVO>> reportMap = Maps.newHashMap();
//
//        for (RuleSupplier ruleSupplier : ruleSupplierList) {
//            String supplierId = ruleSupplier.getSupplierId();
//            String commodityCode = ruleSupplier.getCommodityCode();
//            RuleVO ruleVO = ruleBizService.getDetail(ruleSupplier.getRuleId());
//            if (!Objects.equals(timeType, ruleVO.getTimeType())) {
//                continue;
//            }
//            Supplier supplier = supplierService.getById(supplierId);
//            Integer num = saleStockService.sumTotal(startTime, endTime, supplierId, commodityCode);
//            num = Objects.isNull(num) ? 0 : num;
//
//            List<SaleReportVO> saleReportVOS = reportMap.get(supplierId);
//            if (CollectionUtils.isEmpty(saleReportVOS)) {
//                reportMap.put(supplierId, Lists.newArrayList());
//            }
//            //每一笔商品返利多少
//            SaleReportVO saleReportVO = new SaleReportVO();
//            saleReportVO.setSaleTime(startTime);
//            saleReportVO.setSaleNum(num);
//            saleReportVO.setCommodityName("test");
//            saleReportVO.setCommodityCode(commodityCode);
//            saleReportVO.setSupplierCode(supplier.getSupplierCode());
//            saleReportVO.setSupplierName(supplier.getName());
//            saleReportVO.setTotalPrice(calRebate(ruleVO, num));
//            reportMap.get(supplierId).add(saleReportVO);
//        }
//        for (Map.Entry<String, List<SaleReportVO>> entry : reportMap.entrySet()) {
//            List<SaleReportVO> value = entry.getValue();
//            String key = entry.getKey();
//            Integer totalNum = value.stream().mapToInt(SaleReportVO::getSaleNum).sum();
//            long totalPrice = value.stream().mapToLong(SaleReportVO::getTotalPrice).sum();
//            //每一笔商品返利多少
//            SaleReportVO saleReportVO = new SaleReportVO();
//            saleReportVO.setSaleTime(startTime);
//            saleReportVO.setSaleNum(totalNum);
//            saleReportVO.setSupplierCode("总计");
//            saleReportVO.setTotalPrice(totalPrice / 100);
//            value.add(saleReportVO);
//        }
//        return reportMap.values().stream().flatMap(Collection::stream).collect(Collectors.toList());
//    }

    private BigDecimal calRebate(RuleVO ruleVO, Integer num) {
        BigDecimal price = new BigDecimal(0);
        //1 累加 2顺加
        Integer stairType = ruleVO.getStairType();

        List<RuleVO.RuleLevelVO> ruleLevelList = ruleVO.getRuleLevelList();
        if (Objects.equals(stairType, 2)) {
            for (RuleVO.RuleLevelVO ruleLevelVO : ruleLevelList) {
                Integer minCount = ruleLevelVO.getMinCount();
                Integer maxCount = ruleLevelVO.getMaxCount();
                if (num < minCount) {
                    break;
                }
                if (num < maxCount) {
                    price = price.add(new BigDecimal(num - minCount).multiply(ruleLevelVO.getRebateAmount()));
                } else {
                    price = price.add(new BigDecimal(maxCount - minCount).multiply(ruleLevelVO.getRebateAmount()));
                }
            }
        }
        //累加
        if (Objects.equals(stairType, 1)) {
            for (RuleVO.RuleLevelVO ruleLevelVO : ruleLevelList) {
                Integer minCount = ruleLevelVO.getMinCount();
                Integer maxCount = ruleLevelVO.getMaxCount();
                if (num < minCount) {
                    break;
                }
                if (num < maxCount) {
                    price = price.add(new BigDecimal(num).multiply(ruleLevelVO.getRebateAmount()));
                }
            }
        }

        return price;
    }

    public static void main(String[] args) {
        LocalDateTime localDateTime = LocalDateTime.of(LocalDate.now().minusMonths(1), LocalTime.of(23, 59, 59)).with(TemporalAdjusters.lastDayOfMonth());
        long epochMilli = localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
        System.out.println(epochMilli);

    }

//    /**
//     * 未生效和失效的处理下
//     */
//    private void handlerStatus() {
//        List<RuleSupplier> ruleSupplierList = ruleSupplierService.list(Wrappers.<RuleSupplier>lambdaQuery().in(RuleSupplier::getEffectiveStatus, Lists.newArrayList(EffectiveStatusEnum.ING.getEffectiveStatus(), EffectiveStatusEnum.NO.getEffectiveStatus())));
//        if (CollectionUtils.isEmpty(ruleSupplierList)) {
//            log.info("没有关联的数据");
//            return;
//        }
//        //待处理的列表
//        ArrayList<RuleSupplier> updateRuleSupplierList = Lists.newArrayList();
//        //待生成报表的供应商列表
//        Map<String, List<RuleSupplier>> supplierMap = ruleSupplierList.stream().collect(Collectors.groupingBy(RuleSupplier::getSupplierId));
//
//        //上个月月底
//        LocalDateTime localDateTime = LocalDateTime.of(LocalDate.now().minusMonths(1), LocalTime.of(23, 59, 59, 999)).withDayOfMonth(1);
//        long epochMilli = localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
//
//        for (Map.Entry<String, List<RuleSupplier>> entry : supplierMap.entrySet()) {
//            List<RuleSupplier> ruleSuppliers = entry.getValue();
//            // 供应商 商品分组
//            Map<String, List<RuleSupplier>> commodityCodeMap = ruleSuppliers.stream().collect(Collectors.groupingBy(RuleSupplier::getCommodityCode));
//            for (Map.Entry<String, List<RuleSupplier>> commodityCodeEntry : commodityCodeMap.entrySet()) {
//                List<RuleSupplier> value = commodityCodeEntry.getValue();
//                List<RuleSupplier> collect = value.stream().sorted((r1, r2) -> r1.getEffectiveTime().compareTo(r2.getEffectiveTime())).collect(Collectors.toList());
//                Integer effectiveStatus = collect.get(0).getEffectiveStatus();
//                if (!Objects.equals(EffectiveStatusEnum.NO.getEffectiveStatus(), effectiveStatus)) {
//                    continue;
//                }
//                for (int i = 0; i < collect.size(); i++) {
//                    RuleSupplier ruleSupplier = collect.get(i);
//                    if (i == 0) {
//                        ruleSupplier.setEffectiveStatus(EffectiveStatusEnum.ING.getEffectiveStatus());
//                    } else {
//                        ruleSupplier.setEffectiveStatus(EffectiveStatusEnum.INVALID.getEffectiveStatus());
//                        ruleSupplier.setEffectiveEndTime(epochMilli);
//                    }
//                    updateRuleSupplierList.add(ruleSupplier);
//                }
//            }
//        }
//        ruleSupplierService.updateBatchById(updateRuleSupplierList);
//    }


//    public void generateYear(OutputStream outputStream) {
//        List<Supplier> suppliers = supplierService.list(Wrappers.<Supplier>lambdaQuery().isNotNull(Supplier::getRule));
//        if (CollectionUtils.isEmpty(suppliers)) {
//            log.info("没有设置年返利，不执行");
//            return;
//        }
//
//
//        try (ExcelWriter excelWriter = EasyExcel.write(outputStream, YearSaleReportVO.class).build()) {
//            Long lastDayOfYeah = RebateDateUtil.getLastDayOfYeah();
//            Long firstDayOfYeah = RebateDateUtil.getFirstDayOfYeah();
//            //年报
//            WriteSheet writeSheetYeah = EasyExcel.writerSheet("年报").build();
//            Map<String, Long> totalPriceMap = saleStockService.sumTotalPrice(firstDayOfYeah, lastDayOfYeah);
//            List<YearSaleReportVO> collect = suppliers.stream().map(supplier -> {
//                Long totalPrice = totalPriceMap.get(supplier.getSupplierId());
//                BigDecimal bigDecimal = calYearRebate(supplier, totalPrice);
//                YearSaleReportVO yearSaleReportVO = new YearSaleReportVO();
//                yearSaleReportVO.setSaleTime(new Date(firstDayOfYeah));
//                yearSaleReportVO.setTotalPrice(calYearRebate(supplier, totalPrice));
//                yearSaleReportVO.setSupplierName(supplier.getName());
//                yearSaleReportVO.setSupplierCode(supplier.getSupplierCode());
//                return yearSaleReportVO;
//            }).collect(Collectors.toList());
//
//            excelWriter.write(collect, writeSheetYeah);
//        }
//
//    }


    public List<YearReportVO> generateYear(Long startTime, Long endTime, List<String> supplierIdList) {
        List<Supplier> suppliers = supplierService.list(Wrappers.<Supplier>lambdaQuery()
                .in(CollectionUtils.isNotEmpty(supplierIdList), Supplier::getSupplierId, supplierIdList)
        );
        if (CollectionUtils.isEmpty(suppliers)) {
            log.info("没有设置年返利，不执行");
            return Lists.newArrayList();
        }
        Map<String, Double> totalPriceMap = saleStockService.sumTotalPrice(startTime, endTime, supplierIdList);
        log.info("年报数据:{}", totalPriceMap);
        List<YearReportVO> collect = suppliers.stream().map(supplier -> {
            Double totalPrice = totalPriceMap.get(supplier.getSupplierId());
            YearReportVO yearSaleReportVO = new YearReportVO();
            if (Objects.nonNull(totalPrice)) {
                yearSaleReportVO.setTotalPrice(new BigDecimal(totalPrice));
                yearSaleReportVO.setCashPrice(calYearRebate(supplier, totalPrice));
            } else {
                yearSaleReportVO.setTotalPrice(new BigDecimal(0));
                yearSaleReportVO.setCashPrice(new BigDecimal(0));
            }
            yearSaleReportVO.setSupplierName(supplier.getName());
            yearSaleReportVO.setSupplierCode(supplier.getSupplierCode());
            return yearSaleReportVO;
        }).collect(Collectors.toList());


        return collect;
    }

    private BigDecimal calYearRebate(Supplier supplier, Double yearPrice) {
        Long totalPrice = new BigDecimal(yearPrice).longValue();
        String rule = supplier.getRule();
        if (StringUtils.isEmpty(rule)) {
            return new BigDecimal(0);
        }
        if (Objects.isNull(totalPrice)) {
            return new BigDecimal(0);
        }
        List<RuleLevel> ruleLevels = JSON.parseArray(rule, RuleLevel.class);
        BigDecimal price = new BigDecimal(0);
        for (RuleLevel ruleLevel : ruleLevels) {
            Integer minCount = ruleLevel.getMinCount();
            Integer maxCount = ruleLevel.getMaxCount();
            if (totalPrice >= minCount) {
                price = new BigDecimal(totalPrice).multiply(ruleLevel.getRebateAmount()).divide(new BigDecimal(100));
            }
            continue;
        }
        return price;
    }
}
